package com.nakamachizu.controller.mixi;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;
import org.slim3.datastore.Datastore;
import org.slim3.util.StringUtil;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.nakamachizu.collection.RegisterdMemberSort;
import com.nakamachizu.constant.AppConstant;
import com.nakamachizu.meta.RegisterdMemberDataMeta;
import com.nakamachizu.model.RegisterdMemberData;
import com.nakamachizu.model.session.MixiSessionData;
import com.nakamachizu.service.MapDataService;
import com.nakamachizu.util.ErrorsUtil;
import com.nakamachizu.util.ForwardUtil;

public class MemberController extends Controller {

    private static final Logger log = Logger.getLogger(MemberController.class.getName());
        
    private String to;
    
    private String name;
    
    private String id;
    
    private String cmd_add;
    
    private String cmd_del;
    
    private String sid;
    
    private RegisterdMemberDataMeta meta = RegisterdMemberDataMeta.get();
    
    private List<String>messages;
    @Override
    public Navigation run() throws Exception {
        
        return null;
        /*
        init();
        
        MapDataService mds = new MapDataService();
        MixiSessionData session = mds.getMixiSessionData(sid);
        
        if(!session.isOwner()){
            return redirect("/view?sid=" + sid);
        }
        
        List<RegisterdMemberData>list = Datastore.query(meta)
                                        .filter(meta.adminMailAddress.equal(session.getAdminMailAddress()))
                                        .sort(meta.name.asc)
                                        .asList();
        
        if(!StringUtil.isEmpty(cmd_add) && validate()){
            if(list != null && list.size() >= AppConstant.MAX_REGISTER_NUM()){
                ErrorsUtil.putErrors(errors, request, "message.error.maxregisterd", "max_registerd", AppConstant.MAX_REGISTER_NUM());
            }else{
                if(isNewMember(list, to)){
                    RegisterdMemberData nm = new RegisterdMemberData();
                    nm.setAdminMailAddress(session.getAdminMailAddress());
                    nm.setMailAddress(to);
                    nm.setName(name);
                    Key nmKey = Datastore.put(nm);
                    nm.setKey(nmKey);
                    list.add(nm);
                    Collections.sort(list, new RegisterdMemberSort());
                    addMessages(name + "さんが追加されました。");
                    requestScope("to", null);
                    requestScope("name", null);
                }else{
                    ErrorsUtil.putErrors(errors, request, "message.error.sameaddress", "same_address");
                }
            }
        }

        if(!StringUtil.isEmpty(cmd_del)){
            try{
                Key key = KeyFactory.stringToKey(id);
                RegisterdMemberData data = Datastore.get(RegisterdMemberData.class, key);
                Datastore.delete(key);
                removeMember(list, data.getMailAddress());
                addMessages(data.getName() + "さんを削除しました。");
                
            }catch(Exception e){
                log.info(ErrorsUtil.stackTrace(e));
                ErrorsUtil.putErrors(errors, request, "message.error.memberdelete", "mem_del_error");
            }
        }
        
        requestScope("memberList", list);
        requestScope("messages", messages);
        
        return forward("/jsp/pc/mixi/member.jsp");
        
        */
    }
    
    protected void init(){
        sid = requestScope("sid");
        id = requestScope("id");
        to = requestScope("to");
        name = requestScope("name");
        cmd_add = requestScope("cmd_add");
        cmd_del = requestScope("cmd_del");
        
    }
    
    protected boolean validate() {
        boolean result = false;
        Validators v = new Validators(request);
        if(!StringUtil.isEmpty(cmd_add)){
            v.add("name", v.required());
            v.add("to", v.required());
            if(!StringUtil.isEmpty(to)){
                try{
                    if(!to.contains("@")){
                        throw(new AddressException());
                    }
                    InternetAddress address = new InternetAddress(to);
                }catch(AddressException e){
                    ErrorsUtil.putErrors(errors, request, "message.error.mailaddress", "to", to);
                }
            }
        }
        if(!StringUtil.isEmpty(cmd_del)){
            v.add("id", v.required());
        }

        result = v.validate();
        
        return result;
    }
    
    @Override
    protected Navigation handleError(Throwable error) {
        error.printStackTrace();
        log.severe(ErrorsUtil.stackTrace(error));
        return forward("/jsp/pc/mixi/error.jsp");
    }
    
    protected boolean isNewMember(List<RegisterdMemberData>list, String newAddress){
        boolean result = true;
        if(list != null){
            for(RegisterdMemberData data : list){
                if(data.getMailAddress().equals(newAddress)){
                    result = false;
                }
            }
        }
        return result;
    }
    
    protected void addMessages(String message){
        if(messages == null){
            messages = new ArrayList<String>();
        }
        messages.add(message);
    }
    
    protected void removeMember(List<RegisterdMemberData>list, String mailAddress){
        if(list != null){
            RegisterdMemberData remove = null;
            for(RegisterdMemberData data : list){
                if(data.getMailAddress().equals(mailAddress)){
                    remove = data;
                    break;
                }
            }
            if(remove != null){
                list.remove(remove);
            }
        }
    }
}
